<template>
  <el-dialog
    v-bind:model-value="showPlayer"
    @update:model-value="onModelUpdate"
    title="视频播放"
    width="900px"
    class="player-dialog"
    @close="onClose"
  >
    <div style="width: 100%; height: 500px;">
      <VideoPlayer
        v-if="currentVideo?.recording_url"
        :src="currentVideo.recording_url"
        :autoplay="true"
        :muted="true"
        @ready="onPlayerReady"
        @error="onPlayerError"
        ref="videoPlayer"
      ></VideoPlayer>
      <div v-else class="no-video-tip">
        <el-icon><VideoCamera /></el-icon>
        <span>暂无视频源</span>
      </div>
    </div>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import VideoPlayer from '@/components/VideoPlayer.vue'
import { VideoCamera } from '@element-plus/icons-vue'
import { useRecordingClipping } from './useRecordingClipping'
import { ElMessage } from 'element-plus'

// 定义组件属性
const props = defineProps({
  showPlayer: {
    type: Boolean,
    required: false,
    default: false
  },
  currentVideo: {
    type: Object,
    required: false,
    default: null
  }
})

// 定义组件事件
const emit = defineEmits(['close', 'ready', 'error'])

// 引用
const videoPlayer = ref(null)

// 使用录制拆条功能钩子
const {
  closePlayer,
  onPlayerReady: handlePlayerReady,
  onPlayerError: handlePlayerError
} = useRecordingClipping()

// 处理播放器准备就绪
const onPlayerReady = () => {
  console.log('播放器准备就绪', props.currentVideo?.recording_url)
  emit('ready')
  handlePlayerReady()
}

// 处理播放器错误
const onPlayerError = (error) => {
  console.error('播放器错误', error, props.currentVideo?.recording_url)
  emit('error', error)
  handlePlayerError(error)
}

// 处理弹窗关闭
const onClose = () => {
  console.log('播放器弹窗关闭')
  emit('close')
  closePlayer()
}

// 处理model-value更新
const onModelUpdate = (value) => {
  console.log('播放器弹窗显示状态更新', value)
  emit('update:showPlayer', value)
}

// 监听视频源变化
watch(() => props.currentVideo?.recording_url, (newUrl) => {
  if (newUrl && props.showPlayer) {
    console.log('视频源已更新', newUrl)
    // 如果视频源更新，确保播放器重新加载
    if (videoPlayer.value && typeof videoPlayer.value.play === 'function') {
      // 尝试重新播放视频
      setTimeout(() => {
        videoPlayer.value.play().catch(err => {
          console.warn('自动播放失败，用户交互后可正常播放:', err)
        })
      }, 500)
    }
  }
})
</script>

<style scoped>
.player-dialog .el-dialog__body {
  padding: 0;
}

.no-video-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  background-color: #f5f7fa;
}

.no-video-tip .el-icon {
  margin-right: 8px;
  font-size: 24px;
}
</style>